/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package controle_visao;

import dao.PatrocinadorDAO;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Patrocinador;

/**
 *
 * @author Aluno
 */
public class FRMpatrocinador extends javax.swing.JFrame {

    /**
     * Creates new form patrocinador
     */
    public FRMpatrocinador() {
       initComponents();
         this.patdao = new PatrocinadorDAO();
    
      /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FRMpatrocinador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FRMpatrocinador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FRMpatrocinador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FRMpatrocinador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
         java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FRMpatrocinador().setVisible(true);
            }
        });
         
    
    }
    
    
         
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nomepat = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        telefonepat = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cnpjpat = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        valorpat = new javax.swing.JTextField();
        Cadastro = new javax.swing.JButton();
        Consultar = new javax.swing.JButton();
        Update = new javax.swing.JButton();
        Deletar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("nome");

        jLabel2.setText("telefone");

        jLabel3.setText("cnpj");

        jLabel4.setText("valor");

        Cadastro.setText("cadastrar");
        Cadastro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CadastroActionPerformed(evt);
            }
        });

        Consultar.setText("consultar");
        Consultar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ConsultarActionPerformed(evt);
            }
        });

        Update.setText("alterar");
        Update.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UpdateActionPerformed(evt);
            }
        });

        Deletar.setText("excluir");
        Deletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DeletarActionPerformed(evt);
            }
        });

        jLabel5.setText("id");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(99, 99, 99)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(Consultar)
                            .addComponent(Cadastro))
                        .addGap(79, 79, 79)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(Update)
                            .addComponent(Deletar)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(82, 82, 82)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addGap(18, 18, 18))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel4)
                                            .addComponent(jLabel3)
                                            .addComponent(jLabel5))
                                        .addGap(30, 30, 30)))))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(cnpjpat, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                                .addComponent(nomepat)
                                .addComponent(telefonepat)
                                .addComponent(valorpat))
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(55, 55, 55)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomepat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefonepat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cnpjpat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(valorpat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Cadastro)
                    .addComponent(Update))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Consultar)
                    .addComponent(Deletar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(21, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void CadastroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CadastroActionPerformed

      
        pat.setNome(nomepat.getText());
        pat.setCnpj(cnpjpat.getText());
        pat.setTelefone(telefonepat.getText());
        pat.setValor(Double.parseDouble(telefonepat.getText()));
        pat.setId_patrocinador(Integer.parseInt(jTextField1.getText()));
        patdao.inserir(pat);
        
        
    }//GEN-LAST:event_CadastroActionPerformed

    private void UpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UpdateActionPerformed
        if(nomepat.getText().isEmpty() || telefonepat.getText().isEmpty() || valorpat.getText().isEmpty()){
               JOptionPane.showMessageDialog(rootPane, "Preencha todos os campos do formulário para alterar.");
        }else{
            if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que quer alterar o apoiador?") == 0){
               patdao.alterar(pat);
               ArrayList<Patrocinador>patrocinador = patdao.listar();
               
            }
        }
          
            
       
    }//GEN-LAST:event_UpdateActionPerformed

    private void DeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeletarActionPerformed
        String id_patrocinador = jTextField1.getText();
        if(id_patrocinador.isEmpty()){
           JOptionPane.showMessageDialog(rootPane, "Você deve escolher um apoiador para excluí-lo.");
        }else{
             if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que quer excluir o apoiador") == 0){
               patdao.excluir(Integer.parseInt(id_patrocinador));
               ArrayList<Patrocinador>patrocinador = null;
               patdao.listar();
                excluirLinhasNaTabela(); //excluir linhas na tabela atual
                incluirLinhasNaTabela(patrocinador); //incluir linhas na tabela para que elas possam receber os dados da consulta atual
                preencherTabela(patrocinador);
             }
        }
        
    }//GEN-LAST:event_DeletarActionPerformed

    private void ConsultarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConsultarActionPerformed
         if(nomepat.getText().isEmpty()){
              JOptionPane.showMessageDialog(rootPane, "Nome inválido!");
        }else{
          ArrayList<Patrocinador>patrocinador = patdao.consultar(null);
          if(patrocinador.isEmpty()){
                JOptionPane.showMessageDialog(rootPane, "patrocinador não está cadastrado.");  
          }else{
                excluirLinhasNaTabela(); //excluir linhas na tabela atual
                incluirLinhasNaTabela(patrocinador); //incluir linhas na tabela para que elas possam receber os dados da consulta atual
                preencherTabela(patrocinador);
          }
        }
        
    }//GEN-LAST:event_ConsultarActionPerformed

    
    
     private void excluirLinhasNaTabela(){
        int qdeDeLinhas = jtbConsultaModel.getRowCount(); //a quantidade de linhas deve ser obtida antes de removê-las
        for (int cont=0; cont < qdeDeLinhas; cont++){ //sempre utilize a técnica de controle por contador e utilize como limite a quantidade de linhas presente na tabela (antes da remoção) 
            jtbConsultaModel.removeRow(0); //sempre remova a linha ZERO
        }
    }
    private void incluirLinhasNaTabela( ArrayList<Patrocinador>patrocinador){
        Object[] linha = new Object[5]; //cria um array de objetos com o tamanho da quantidade de campos (colunas) da tabela
        for(int c=0; c < patrocinador.size(); c++){
            jtbConsultaModel.addRow(linha); //adiciona linhas na tabela até o tamanho do arrayList (que contém os dados de uma consulta do tipo listar)
        }
    }
     private void preencherTabela(ArrayList<Patrocinador>patrocinador){
        //adiciona os valores da consulta nas linhas da tabela
        int row = 0;        
        for (Patrocinador patr : patrocinador) { //usa um for-each para percorrer o arrayList e alimentar a camada de modelo da JTable 
            jtbConsultaModel.setValueAt(patr.getNome(),row ,0);
            jtbConsultaModel.setValueAt(patr.getCnpj(),row,1);
            jtbConsultaModel.setValueAt(patr.getTelefone(),row,2);
            jtbConsultaModel.setValueAt(patr.getValor(),row,3);
            jtbConsultaModel.setValueAt(patr.getId_patrocinador(),row,4);
            row++;
        }  
    }
    /**
     * @param args the command line arguments
     */
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Cadastro;
    private javax.swing.JButton Consultar;
    private javax.swing.JButton Deletar;
    private javax.swing.JButton Update;
    private javax.swing.JTextField cnpjpat;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField nomepat;
    private javax.swing.JTextField telefonepat;
    private javax.swing.JTextField valorpat;
    // End of variables declaration//GEN-END:variables
   
    
      Patrocinador pat = new Patrocinador();
      PatrocinadorDAO patdao = new PatrocinadorDAO();
      DefaultTableModel jtbConsultaModel;
}
